import { ref } from 'vue'

export default () => {
  const comps = ref<CompModel[]>([])
  const comp = ref<CompModel>()

  const all = async () => {
    comps.value = await window.api.sql(`select * from comps order by id desc`, 'findAll')
  }

  const add = async (data: CompModel) => {
    return await window.api.sql<number>(
      `insert into comps (name,shortName,fr,sjfzr,created_at) values(@name,@shortName,@fr,@sjfzr,datetime())`,
      'insert',
      {
        name: data.name,
        shortName: data.shortName,
        fr: data.fr,
        sjfzr: data.sjfzr
      }
    )
  }

  const find = async (id: number) => {
    comp.value = await window.api.sql(`select * from comps where id=@id`, 'findOne', { id })
  }

  const update = async (data: CompModel) => {
    await window.api.sql(
      `update comps set name=@name,shortName=@shortName,fr=@fr,sjfzr=@sjfzr where id=@id`,
      'update',
      {
        id: data.id,
        name: data.name,
        shortName: data.shortName,
        fr: data.fr,
        sjfzr: data.sjfzr
      }
    )
  }

  return { all, add, find, update, comp, comps }
}
